package com.wb.listening

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper
import com.wb.component.Slf4j.Companion.log
import com.wb.component.astrict.Astrict
import com.wb.component.event.MsgSend
import com.wb.component.event.OnGroup
import com.wb.component.filter.FunFilter
import com.wb.component.filter.FunFilterType
import com.wb.component.filter.FunFilters
import com.wb.config.AOPConfig
import com.wb.entity.MsgGet
import com.wb.entity.RevokeMsg
import com.wb.pojo.GroupUserLangOcr
import com.wb.pojo.WeAndQqUserLang
import com.wb.service.GroupUserLangOcrService
import com.wb.service.WeAndQqUserLangService
import com.wb.utils.*
import com.wb.utils.encryption.Md5Encryption
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Component
import org.springframework.web.client.RestTemplate
import java.io.File
import java.util.concurrent.TimeUnit
import javax.annotation.Resource

@Component
open class GroupMsgListening {

    @Value("\${com.bot.read.charset}")
    lateinit var charset: String

    @Value("\${com.bot.group.user.lang.path}")
    lateinit var groupUserLangPath: String

    @Value("\${com.bot.group.user.lang.url}")
    lateinit var groupUserLangUrl: String

    @Value("\${com.bot.moyu.path}")
    lateinit var moyuPath: String

    @Value("\${com.bot.video.path}")
    lateinit var videoPath: String

    @Autowired
    lateinit var weAndQqUserLangService: WeAndQqUserLangService

    @Autowired
    lateinit var groupUserLangOcrService: GroupUserLangOcrService

    @OnGroup
    @FunFilters(
        value = arrayOf(
            FunFilter(key = "网抑云", type = FunFilterType.START_WITH),
            FunFilter(key = "网易云", type = FunFilterType.START_WITH),
            FunFilter(key = "网抑热评", type = FunFilterType.START_WITH),
            FunFilter(key = "网易热评", type = FunFilterType.START_WITH)
        )
    )
    open fun wyMusic(msgGet: MsgGet?) {

        val text = msgGet!!.msg
        // 获取到音乐名称
        val keyword = text.replace(Regex(".*(网抑云|网易云|热评|网抑|网易)+?"), "").trim()

        val isComment = text.contains(Regex("网易热评|网抑热评"))

        if (keyword.isEmpty()) {
            if (isComment) {
                MsgSend.sendText(msgGet.from_wxid, "请在【网易热评|网抑热评】后面填写搜索词")
            } else {
                MsgSend.sendText(msgGet.from_wxid, "请在【网抑云|网易云】后面填写搜索词")
            }
            return
        }

        try {
            val songs = WYMusicUtil.searchMusic(keyword, 0)
            var sendMsg = ""
            if (songs.size > 0) {
                val song = songs.get(0);
                if (isComment) {
                    sendMsg = WYMusicUtil.getHotMusicComment(song)
                    MsgSend.sendText(msgGet.from_wxid, sendMsg)
                } else {
                    val ar = song.ar.map { it.name }
                        .joinToString(" ")
                    MsgSend.sendLink(
                        msgGet.from_wxid,
                        song.name,
                        ar,
                        WYMusicUtil.WY_DATA_MAP.get("jumpUrl") + song.id,
                        if (song.al != null) song.al!!.picUrl else "",
                        ""
                    )
                }
                return
            }
            MsgSend.sendText(msgGet.from_wxid, if (isComment) "很抱歉,暂未搜索到该歌曲热评" else "很抱歉,暂未搜索到该歌曲")
        } catch (e: Exception) {
            log.error("搜索网抑云出现错误", e)
            MsgSend.sendText(msgGet.from_wxid, "搜索出错啦")
        }
    }

    @OnGroup
    @FunFilter(key = "土味情话", type = FunFilterType.EQ)
    open fun earthWords(msg: MsgGet?) {

        val text = DogLogUtil.getInFileByRes("earthy_words.json", charset(charset))

        if (text.isEmpty()) {
            MsgSend.sendText(msg!!.from_wxid, "暂未读取到土味情话")
            return
        }

        MsgSend.sendText(msg!!.from_wxid, text)
    }

    @OnGroup
    @FunFilters(
        value = arrayOf(
            FunFilter(key = "毒鸡汤", type = FunFilterType.EQ),
            FunFilter(key = "心灵鸡汤", type = FunFilterType.EQ)
        )
    )
    open fun ikun(msg: MsgGet?) {
        val list = ResourceUtil.readLinesByRes("poison_kun.txt", charset(charset))

        if (list.isNullOrEmpty()) {
            MsgSend.sendText(msg!!.from_wxid, "鸡汤还没煲好,请稍后")
            return
        }

        val text = list.get((Math.random() * list.size).toInt())

        MsgSend.sendText(msg!!.from_wxid, text)
    }

    /**
     * 群友语录 - 来源于QQ群 需要绑定 group_user_lang_ocr
     */
    @OnGroup
    @FunFilter(key = "群友语录", type = FunFilterType.START_WITH)
    open fun groupUserLang(msg: MsgGet) {

        val text = msg.msg

        val word = text.substring(4)
        // 查找关联
        val groups = weAndQqUserLangService.list(QueryWrapper<WeAndQqUserLang>().apply {
            eq("we_group", msg.from_wxid)
        })

        if (groups.size == 0) {
            MsgSend.sendText(msg.from_wxid, "暂未绑定群友语录")
            return
        }

        if (word.isNotBlank()) {

            // 根据关键词搜索
            val langs = groupUserLangOcrService.list(QueryWrapper<GroupUserLangOcr>().apply {
                like("txt", word)
                    .and { q ->
                        q.`in`("group_num", groups.map { it.qqGroup })
                    }
            })
            if (langs.size != 0) {
                // 随机选择一个
                val lang = langs.get(
                    (Math.random() * langs.size).toInt()
                )

                val path = groupUserLangPath + File.separator + lang.groupNum

                val file = File(path, lang.fileName!!)

                val url = "${groupUserLangUrl}${lang.groupNum}/${lang.fileName}"

                MsgSend.sendImage(
                    msg.from_wxid,
                    lang.fileName,
                    url,
                    file.absolutePath
                )
                return
            }

        }

        val group = groups.get(
            (Math.random() * groups.size).toInt()
        )

        val path = groupUserLangPath + File.separator + group.qqGroup

        val file = File(path)

        val files = file.listFiles()
        file.parentFile.mkdirs()
        if (files.isNullOrEmpty()) {
            MsgSend.sendText(msg.from_wxid, "暂未收录语录")
            return
        }
        // 随机选择一张
        val fileImg = files.get(
            (Math.random() * files.size).toInt()
        )

        val url = "${groupUserLangUrl}${group.qqGroup}/${fileImg.name}"

        MsgSend.sendImage(
            msg.from_wxid,
            fileImg.name,
            url,
            fileImg.absolutePath
        )

    }

    @OnGroup
    @FunFilter(key = "摸鱼日历", type = FunFilterType.EQ)
    open fun moyu(msg: MsgGet) {

        val file = TouchFishUtil.getImgFile(moyuPath)

        if (file == null) {
            MsgSend.sendText(msg.from_wxid, "暂未获取到摸鱼日历")
            return
        }

        MsgSend.sendImage(
            msg.from_wxid,
            file.name,
            "",
            file.absolutePath
        )

    }

    @OnGroup
    @FunFilters(
        value = arrayOf(
            FunFilter(key = "西瓜", type = FunFilterType.START_WITH),
            FunFilter(key = "sp", type = FunFilterType.START_WITH),
            FunFilter(key = "xg", type = FunFilterType.START_WITH)
        )
    )
    @Astrict(time = 5, timeUnit = TimeUnit.MINUTES)
    open fun video(msg: MsgGet) {
        val key = msg.msg.substring(2)

        if (key.isBlank()) {
            MsgSend.sendText(msg.from_wxid, "请在【西瓜|xg|sp】后面添加搜索词")
            return
        }

        try {
            MsgSend.sendText(msg.from_wxid, "启动西瓜视频搜索，请稍后")
            val file = XiGuaVideo.search(key, videoPath)

            if (file == null || !file.exists()) {
                MsgSend.sendText(msg.from_wxid, "暂未搜索到视频")
                return
            }

            MsgSend.sendVideo(
                msg.from_wxid,
                file.name,
                "",
                file.absolutePath
            )

        } catch (e: Exception) {
            log.error("搜索视频出现错误", e)

            MsgSend.sendText(msg.from_wxid, "搜索西瓜视频失败")
        }

    }

}